package code.framework.android.core;

import java.io.Serializable;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import code.framework.android.activity.MaskActivity;
import code.framework.android.data.ApplicationPreference;

import com.google.inject.Inject;

/**
 * should beware synchronization problem
 */
public class ApplicationContextImpl implements ApplicationContext {

	private Toast toast;
	
	@Inject
	private ApplicationPreference applicationPreference;

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public void sendModalMessage(String message, Context context) {
		final Intent intent = new Intent(context, MaskActivity.class);
		intent.putExtra(MESSAGE, message);
		context.startActivity(intent);
	}

	public void sendSerializableCollection(Collection<?> collection,
			Handler handler) {
		if (collection != null && collection.size() > 0) {
			for (Serializable serializable : (Collection<Serializable>) collection) {
				sendSerializable(serializable, handler);
			}
		}
	}

	public void sendSerializable(Serializable serializable, Handler handler) {
		if (Serializable.class.isAssignableFrom(serializable.getClass())) {
			final Bundle b = new Bundle();
			b.putSerializable(serializable.getClass().getSimpleName(),
					serializable);
			final Message msg = Message.obtain(handler);
			msg.setData(b);
			msg.sendToTarget();
		}
	}

	public void startIntentWithAKey(Context context, Class<?> target,
			String key, Integer value) {
		final Intent i = new Intent(context, target);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.putExtra(key, value);
		context.startActivity(i);
	}

	/**
	 * toast is discourage for the reason of distributing
	 * 
	 * @param message
	 * @param context
	 */
	public void sendToastMessage(String message, Context context) {
		if (toast != null) {
			logger.trace("cancel toast");
			toast.cancel();
		}
		logger.trace("invoke toast");
		toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
	}

	public ApplicationPreference getApplicationPreference() {
		return applicationPreference;
	}

	public void setApplicationPreference(ApplicationPreference applicationPreference) {
		this.applicationPreference = applicationPreference;
	}

}
